#include "filestream.h"
#include "util/assert.h"

namespace gecko
{

	// -----------------------------------------------------------------------------------------------

	FileStream::FileStream( const char* filename, eMode mode )
		: m_fileHandle(0)
	{
		m_mode = mode;

		switch ( m_mode )
		{
		case ModeRead:
			m_fileHandle = fopen(filename, "r+b");
			Assert(m_fileHandle, "File could not be opened");
			break;

		case ModeWrite:
			m_fileHandle = fopen(filename, "w+b");
			break;

		default:
			Error("Unhandled mode");
			break;
		}
	}

	// -----------------------------------------------------------------------------------------------

	void FileStream::Close()
	{
		if ( m_fileHandle )
		{
			fclose(m_fileHandle);
			m_fileHandle = 0;
		}
	}

	// -----------------------------------------------------------------------------------------------

	FileStream::~FileStream()
	{
		Close();
	}

	// -----------------------------------------------------------------------------------------------

	bool FileStream::Seek(size_t offset, eSeekPos origin)
	{
		return fseek(m_fileHandle, (long)offset, origin) == 0;
	}

	// -----------------------------------------------------------------------------------------------

	size_t FileStream::ReadBuffer( char* buffer, size_t len )
	{
		return fread(buffer, 1, len, m_fileHandle);
	}

	// -----------------------------------------------------------------------------------------------

	size_t FileStream::WriteBuffer( char* buffer, size_t len )
	{
		return fwrite(buffer, 1, len, m_fileHandle);
	}

	// -----------------------------------------------------------------------------------------------

	size_t FileStream::SerialiseBuffer( char* buffer, size_t len )
	{
		size_t bytesSerialised = 0;

		switch (m_mode)
		{
		case ModeRead:
			bytesSerialised = fread(buffer, 1, len, m_fileHandle);
			break;

		case ModeWrite:
			bytesSerialised = fwrite(buffer, 1, len, m_fileHandle);
			break;
		}

		return bytesSerialised;
	}

	// -----------------------------------------------------------------------------------------------

	size_t FileStream::GetPosition()
	{
		return ftell(m_fileHandle);
	}

}
